
import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { Assist } from '../../model/report/assist';
import { Fault } from '../../model/report/fault';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import 'rxjs/add/operator/toPromise';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
declare const $: any;
import * as Enumerable from 'linq';
import { DxDropDownBoxComponent } from 'devextreme-angular';
@Component({
    selector: 'app-report-andon',
    templateUrl: './andon.component.html',
    styleUrls: ['./andon.component.scss']
})

export class AndonComponent implements OnInit {
    // 变量定义
    title = 'Andon分析';
    public assistList: Assist[];
    public faultList: any[];
    public faultTopCount = 3;
    public assistTopCount = 3;
    // 界面显示数据定义
    public faultChartList: Fault[];
    public assistTopList: any[];
    public faultTopList: any[];
    public faultChartOption: any;
    public assistChartOption: any;

    showloading = true;

    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
     public equipemntItems: TVResource[] = [];

    public subAreaSelected: any[];
    public shiftSelected: any;
    public equipmentSelected: TVResource[] = [];
     


    typeList: any = [
        { id: 1, name: '单周' },
        { id: 2, name: '双周' },
    ];

    public tpmItems = [{ id: 1, text: 'N' }, { id: 0, text: 'Y' }];
    public type = 1;

    public curTime = new Date();


    @ViewChild('ddda') dddaS: DxDropDownBoxComponent
    clearSubAreaSelected() {
        this.subAreaSelected = [];
    }
    subAreaSelectedOk() {
        this.dddaS.instance.close();
    }

    constructor(private commServices: CommService) {
    }
    // 组件初始化
    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD');
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAreaSelected = [];
        this.equipemntItems = this.commServices.getandonResourceBySubArea(this.subAreaItems[0].subArea);
        this.subAreaSelected.forEach(e => {
            const arr = this.commServices.getTVResourceBySubArea(e.subArea);
            arr.forEach(a => { this.equipemntItems.push(a); });
        });
    }
    @ViewChild('dddb') dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }

    onSubAreaSelectedChange(subArea: any): void {
        this.equipemntItems = [];
        this.subAreaSelected.forEach(e => {
            const arr = this.commServices.getandonResourceBySubArea(e.subArea);
            debugger
            arr.forEach(a => { this.equipemntItems.push(a); });
        });

        this.equipmentSelected = [];

        //this.initTemplate();
    }


    /**
         * 获取表格数据
         */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = this.subAreaSelected.map(item => item.subArea);
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        this.commServices
            .getList(queryModel, ReportUrls.FaultUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.faultList = model.data;
                    this.faultList.map(e => {
                        if(queryModel.querySubAreaIds[0].slice(0,2) === 'GF'){
                            var sub: string = '';
                            sub = e.subArea.replace(/(^\s*)|(\s*$)/g, "");
                            switch(sub){
                                case 'GFAL1': sub += '_装配主线';  break;
                                case 'GFBU1': sub += '_测试线';  break;
                                case 'GFCL1': sub += '_CASE 机加工线';  break;
                                case 'GFCR1': sub += '_行星齿轮组分装线';  break;
                                case 'GFCS1': sub += '_中间支撑架分装线';  break;
                                case 'GFDH1': sub += '_飞轮盘减震器壳体分装线';  break;
                                case 'GFHL1': sub += '_HOUSING 机加工线';  break;
                                case 'GFTC1': sub += '_壳体分装线';  break;
                                case 'GFTD1': sub += '_中间轴&差速器分装线';  break;
                            }
                            e.subArea = sub;
                        }
                        e.subArea = e.subArea.slice(2, e.subArea.length);
                        e.station = e.station.replace(new RegExp('_', "gm"), '');
                    })
                    this.faultList = this.faultList.filter(e => e.reportFilter === true);
                    this.getFaultChartList();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
        // 获取Andon求助信息并显示
        this.commServices
            .getList(queryModel, ReportUrls.AssistUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    debugger
                    this.assistList = model.data;
                    this.assistList.map(e => {
                        e.subArea = e.subArea.slice(2, e.subArea.length);
                        e.equipment = e.equipment.replace(new RegExp('_', "gm"), '');
                    })
                    this.getAssistChartList();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    private getFaultChartList() {
        const tempList = new Array<Fault>();
        let groupFault = new Fault();
        groupFault.resource = '';
        groupFault.shiftId = 0;
        Enumerable.from(this.faultList).orderBy(u => u.resource).thenBy(u => u.shiftId).toArray().forEach(u => {
            if (u.resource !== groupFault.resource || u.shiftId !== groupFault.shiftId) {
                if (groupFault.resource !== '') {
                    groupFault.duration = Number.parseFloat((groupFault.duration / 60).toFixed(2));
                    tempList.push(groupFault);
                }
                groupFault = new Fault();
                groupFault.resource = u.resource;
                groupFault.shiftId = u.shiftId;
                groupFault.station = u.subArea + '-' + u.station;
                groupFault.duration = u.duration;
            } else {
                groupFault.duration = groupFault.duration + u.duration;
            }
        });
        const sumShiftList = Enumerable.from(tempList).groupBy(u => u.resource)
            .select(u => {
                const temp: Fault = new Fault();
                temp.resource = u.first().resource;
                temp.station = u.first().station;
                temp.duration = Number.parseFloat(u.sum(item => item.duration).toFixed(2));
                return temp;
            }).orderByDescending(u => u.duration).toArray();
        this.faultChartList = Enumerable.from(tempList).orderByDescending(u => u.duration).toArray();
        this.showFaultChart(sumShiftList);
        this.faultTopList = sumShiftList.slice(0, this.faultTopCount);
        this.faultTopList.forEach((e) => {
            e.type = 'fault';
            e.timerange = this.getTime('DateTimeRange');
            // e.subArea = this.subAreaSelected.map(item=>item.subArea);
            e.id = e.station;
            this.commServices
                .doPost('/andontop/find', e)
                .subscribe(model => {
                    if (model.resultCode === 200) {
                        e.reason = model.data.reason;
                        e.solveWay = model.data.solveWay;
                        e.resUser = model.data.resUser;
                        e.targetTime = model.data.targetTime;
                        e.completeTime = model.data.completeTime;
                        e.status = model.data.status;
                        e.resultStatus = model.data.resultStatus;
                    }
                });
        });
    }
    private getAssistChartList() {
        const tempList = new Array<Assist>();
        let groupAssist = new Assist();
        groupAssist.resource = '';
        groupAssist.shiftId = 0;
        Enumerable.from(this.assistList).orderBy(u => u.resource).thenBy(u => u.shiftId).toArray().forEach(u => {
            if (u.resource !== groupAssist.resource || u.shiftId !== groupAssist.shiftId) {
                if (groupAssist.resource !== '') {
                    groupAssist.intervalTime = Number.parseFloat((groupAssist.intervalTime / 60).toFixed(2));
                    tempList.push(groupAssist);
                }
                groupAssist = new Assist();
                groupAssist.operationNo = u.operationNo;
                groupAssist.resource = u.resource;
                groupAssist.shiftId = u.shiftId;
                groupAssist.equipment = u.subArea + '-' + u.equipment;
                groupAssist.intervalTime = u.intervalTime;
                groupAssist.count = 1;
            } else {
                groupAssist.intervalTime = groupAssist.intervalTime + u.intervalTime;
                groupAssist.count = groupAssist.count + 1;
            }
        });
        const sumShiftList = Enumerable.from(tempList).groupBy(u => u.operationNo)
            .select(u => {
                const temp: Assist = new Assist();
                temp.operationNo = u.first().operationNo;
                temp.resource = u.first().resource;
                temp.equipment = u.first().equipment;
                temp.intervalTime = Number.parseFloat(u.sum(item => item.intervalTime).toFixed(2));
                temp.count = u.sum(u=>u.count);
                return temp;
            }).orderByDescending(u => u.count).toArray();
        this.showAssistChart(sumShiftList);
        this.assistTopList = sumShiftList.slice(0, this.assistTopCount);
        this.assistTopList.forEach((e) => {
            e.type = 'assist';
            e.timerange = this.getTime('DateTimeRange');
            // e.subArea = this.subAreaSelected.map(item=>item.subArea);
            e.station = e.equipment;
            e.duration = e.count;
            this.commServices
                .doPost('/andontop/find', e)
                .subscribe(model => {
                    if (model.resultCode === 200) {
                        e.reason = model.data.reason;
                        e.solveWay = model.data.solveWay;
                        e.resUser = model.data.resUser;
                        e.targetTime = model.data.targetTime;
                        e.completeTime = model.data.completeTime;
                        e.status = model.data.status;
                        e.resultStatus = model.data.resultStatus;

                    }
                });
        });
    }
    /**
     * 获取TimeRange的值
     * @param id id
    */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        // const timeArray: Array<String> = timerange.split(' - ');
        return timerange;
    }

    /**ECharts图表相关*/
    chartsMap = new Map<any, any>();
    onChartInit(index: any, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }
    private showFaultChart(sumShiftList: Array<Fault>): void {
        const xData = new Array();
        const shift1List = new Array();
        const shift2List = new Array();
        const shift3List = new Array();
        const legend = new Array();
        const series = new Array();
        let shift1HasData: boolean = false;
        let shift2HasData: boolean = false;
        let shift3HasData: boolean = false;
        for (let i = 0; i < sumShiftList.length; i++) {
            const temp: Fault = sumShiftList[i];
            xData.push(temp.station);
            const tempList = Enumerable.from(this.faultChartList).where(u => u.resource === temp.resource).toArray();
            if (tempList.find(u => u.shiftId === 1) !== undefined) {
                shift1List.push(tempList.find(u => u.shiftId === 1).duration);
                shift1HasData = true;
            } else {
                shift1List.push(0);
            }
            if (tempList.find(u => u.shiftId === 2) !== undefined) {
                shift2List.push(tempList.find(u => u.shiftId === 2).duration);
                shift2HasData = true;
            } else {
                shift2List.push(0);
            }
            if (tempList.find(u => u.shiftId === 3) !== undefined) {
                shift3List.push(tempList.find(u => u.shiftId === 3).duration);
                shift3HasData = true;
            } else {
                shift3List.push(0);
            }
        };
        if (shift1HasData) {
            legend.push('早班');
            series.push(
                {
                    name: '早班',
                    type: 'bar',
                    stack: '班次',
                    data: shift1List
                }
            );
        }
        if (shift2HasData) {
            legend.push('中班');
            series.push(
                {
                    name: '中班',
                    type: 'bar',
                    stack: '班次',
                    data: shift2List
                }
            );
        }
        if (shift3HasData) {
            legend.push('晚班');
            series.push(
                {
                    name: '晚班',
                    type: 'bar',
                    stack: '班次',
                    data: shift3List
                }
            );
        }
        this.faultChartOption = ChartOptionCreater.createStackedColumnOption('', '', '分', legend, xData, series);//故障/停线时间分析
        // this.showloading = false;
    }
    private showAssistChart(sumShiftList: Array<Assist>): void {
        const xData = new Array();
        const shift1List = new Array();
        const shift2List = new Array();
        const shift3List = new Array();
        const legend = new Array();
        const series = new Array();
        let shift1HasData = false;
        let shift2HasData = false;
        let shift3HasData = false;
        for (let i = 0; i < sumShiftList.length; i++) {
            const temp: Assist = sumShiftList[i];
            xData.push(temp.operationNo);
            const tempList = Enumerable.from(this.assistList).where(u => u.operationNo === temp.operationNo).toArray();
            if (tempList.find(u => u.shiftId === 1) !== undefined) {
                shift1List.push(tempList.filter(u => u.shiftId === 1).length);
                shift1HasData = true;
            } else {
                shift1List.push(0);
            }
            if (tempList.find(u => u.shiftId === 2) !== undefined) {
                shift2List.push(tempList.filter(u => u.shiftId === 2).length);
                shift2HasData = true;
            } else {
                shift2List.push(0);
            }
            if (tempList.find(u => u.shiftId === 3) !== undefined) {
                shift3List.push(tempList.filter(u => u.shiftId === 3).length);
                shift3HasData = true;
            } else {
                shift3List.push(0);
            }
        };
        if (shift1HasData) {
            legend.push('早班');
            series.push(
                {
                    name: '早班',
                    type: 'bar',
                    stack: '班次',
                    data: shift1List
                }
            );
        }
        if (shift2HasData) {
            legend.push('中班');
            series.push(
                {
                    name: '中班',
                    type: 'bar',
                    stack: '班次',
                    data: shift2List
                }
            );
        }
        if (shift3HasData) {
            legend.push('晚班');
            series.push(
                {
                    name: '晚班',
                    type: 'bar',
                    stack: '班次',
                    data: shift3List
                }
            );
        }
        this.assistChartOption = ChartOptionCreater.createStackedColumnOption('', '', '次数', legend, xData, series); // 呼叫次数分析
        // this.showloading = false;
    }

    saveCountAnalyse() {
        this.assistTopList.forEach(e => {
            e.type = 'assist';
            e.timerange = this.getTime('DateTimeRange');
            // e.subArea = this.subAreaSelected.map(item=>item.subArea);
            e.station = e.equipment;
        });
        this.commServices
            .doPost('/andontop/refresh', this.assistTopList)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    alert('更新成功');
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    saveTimeAnalyse() {
        this.faultTopList.forEach(e => {
            e.type = 'fault';
            e.timerange = this.getTime('DateTimeRange');
            // e.subArea = this.subAreaSelected.map(item=>item.subArea);
        });
        this.commServices
            .doPost('/andontop/refresh', this.faultTopList)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    alert('更新成功');
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    /**对页面数据进行导出 */
    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        const tables = new Array<any>();

        const row1 = new Array();
        this.faultTopList.forEach((e: any) => {
            const co = new Array();
            co.push(e.duration);
            co.push(e.station);
            co.push(e.reason);
            co.push(e.solveWay);
            co.push(e.resUser);
            co.push(e.targetTime);
            co.push(e.completeTime);
            co.push(e.status);
            co.push(e.resultStatus);
            row1.push(co);
        });
        const table1 = {
            tableName: '故障/停机时间（TOP3）',
            titles: ['故障时间(分)', '工位号', '原因', '措施', '责任人', '计划完成时间', '实际完成时间', '状态', '改进效果'],
            rows: row1,
            sort: 2,
            nextNewPage: 2
        };

        const row2 = new Array();
        this.assistTopList.forEach((e: any) => {
            const co = new Array();
            co.push(e.count);
            co.push(e.equipment);
            co.push(e.reason);
            co.push(e.solveWay);
            co.push(e.resUser);
            co.push(e.targetTime);
            co.push(e.completeTime);
            co.push(e.status);
            co.push(e.resultStatus);
            row2.push(co);
        });
        const table2 = {
            tableName: '呼叫次数（TOP3）',
            titles: ['呼叫次数', '工位号', '原因', '措施', '责任人', '计划完成时间', '实际完成时间', '状态', '改进效果'],
            rows: row2,
            sort: 4,
            nextNewPage: 2
        };

        tables.push(table1);
        tables.push(table2);

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAreaSelected.map(item => item.subArea));
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            const s = (k === '故障/停机时间分析') ? 1 : 3;
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info, sort: s });
        });

        const upload = {
            reportTitle: this.title,
            charts: files,
            queryModel: queryModelArray,
            tables: tables
        };

        this.commServices.exportPdf(upload);
    }


    public updateAssistRow = [];
    onUpdateAssistRow(e) {
        this.updateAssistRow.push(e.key)
    }

    saveChanges(){
        this.commServices
                .doPost('/assist/update', this.updateAssistRow)
                .subscribe(model => {
                    if (model.resultCode === 200 && model.data) {
                        this.updateAssistRow = [];
                        this.getReportData();
                    }
                });
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }

}
